
/**
 * 查询目标表累计收到数据条数（实际是查询test_target.orders_target的记录数)
 */
function querySinkTarget() {
    fetch('/orders/countTargetOrder', {
        method: 'GET',
        headers: {
            "auth2045": getLoginToken()
        }
    })
        .then(response => response.json())
        .then(data => {
            addMessageToFlinkOut("目标表累计收到数据:" + data.data + "条");
        });
}

/**
 * 释放发送数据库数据到MQTT服务器过程中添加的锁，避免死锁
 * @param {*} callback 回调
 */
function releaseLock(callback) {
    fetch('/orders/release-mqttlock', {
        method: 'GET',
        headers: {
            "auth2045": getLoginToken()
        }
    })
        .then(response => response.json())
        .then(data => {
            addMessageToWebsocketOut(data.message);
            if (data.data && callback) {
                callback();
            }
        });
}


/**
 * 发送数据到MQTT服务器
 * @param {*} urlParams url参数列表，例如：new URLSearchParams('name=abc&age=18')
 * @param {*} callback 回调
 */
function sendToMqtt(urlParams, callback, body) {
    console.log(body);
    if (body == undefined || body == null) {
        body = {}
    }
    fetch(`/orders/start-send-to-mqtt?${urlParams.toString()}`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            "auth2045": getLoginToken()
        },
        body: JSON.stringify(body)
    })
        .then(response => response.json())
        .then(data => {
            alert(data.message);
            if (data.flag == 1) {
                if (callback) {
                    callback();
                }
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('发送数据到MQTT失败!');
        });
}

// websocket输出到dom有关函数
function addMessageToWebsocketOut(message) {
    writeMessage(message, 'wsMessages');
}

function addMessageToFlinkOut(message) {
    writeMessage(message, 'flinkOutput');
}

function writeMessage(message, boxId) {
    const messagesDiv = document.getElementById(boxId);
    const messageElement = document.createElement('div');
    messageElement.textContent = message;
    messagesDiv.appendChild(messageElement);

    // 限制最多显示20条消息
    const messages = messagesDiv.children;
    if (messages.length > 20) {
        messagesDiv.removeChild(messages[0]);
    }
    messagesDiv.scrollTop = messagesDiv.scrollHeight;
}    